<template>
  <div class="disease-management">
    <el-row :gutter="20">
      <!-- 左侧树形结构 -->
      <el-col :span="8">
        <el-card>
          <div slot="header" class="card-header">
            <span>疾病分类结构</span>
            <div class="header-buttons">
              <el-button type="primary" size="mini" @click="addRootCategory">添加大类</el-button>
              <el-button type="success" size="mini" @click="exportToExcel">导出Excel</el-button>
              <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
              >
                <el-button type="warning" size="mini">导入Excel</el-button>
              </el-upload>
            </div>
          </div>
          <el-tree
            :data="diseaseTree"
            node-key="id"
            :props="treeProps"
            :expand-on-click-node="false"
            draggable
            @node-drop="handleDrop"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <el-button type="text" size="mini" @click.stop="() => append(data)">添加</el-button>
                <el-button type="text" size="mini" @click.stop="() => edit(data)">编辑</el-button>
                <el-button type="text" size="mini" @click.stop="() => remove(node, data)">删除</el-button>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="16">
        <el-card v-if="currentNode">
          <div slot="header">
            <span>{{ currentNode.type === 'disease' ? '疾病详情' : '分类详情' }}</span>
          </div>
          <div v-if="currentNode.type === 'category'">
            <h3>{{ currentNode.label }} (分类)</h3>
            <p>描述信息...</p>
          </div>
          <div v-else>
            <h3>{{ currentNode.label }} (疾病)</h3>
            <el-tabs>
              <el-tab-pane label="基本信息">
                <el-form :model="currentNode" label-width="120px">
                  <el-form-item label="疾病描述">
                    <el-input
                      type="textarea"
                      :rows="3"
                      v-model="currentNode.description"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="百科链接">
                    <!-- 移除输入框，链接动态生成 -->
                    <el-button type="text" @click="openWikiLink">访问百科</el-button>
                  </el-form-item>
                </el-form>
                <el-button type="primary" @click="saveBasicInfo">保存基本信息</el-button>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
        <!-- 移除百科链接输入框 -->
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDialog">确定</el-button>
      </div>
    </el-dialog>
  
  </div>
</template>

<script>
// 引入导出方法
import { exportJsonToExcel } from '@/utils/export2Excel.js';
import * as XLSX from 'xlsx';

export default {
  name: 'DiseaseCategoryManagement',
  data() {
    return {
      diseaseTree: [],
      treeProps: {
        label: 'label',
        children: 'children'
      },
      currentNode: null,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        name: '',
        description: '',
        type: 'category',
        parentId: null,
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ]
      },
      nextId: 1
    }
  },
  methods: {
    // 原有方法保持不变
    addRootCategory() {
      this.dialogTitle = '添加疾病大类'
      this.form = {
        name: '',
        description: '',
        type: 'category',
        parentId: null,
      }
      this.dialogVisible = true
    },
    append(data) {
      this.dialogTitle = data.type === 'category' ? '添加子分类' : '添加疾病'
      this.form = {
        name: '',
        description: '',
        type: data.type === 'category' ? 'category' : 'disease',
        parentId: data.id,
      }
      this.dialogVisible = true
    },
    edit(data) {
      this.dialogTitle = `编辑${data.type === 'category' ? '分类' : '疾病'}`
      this.form = {
        name: data.label,
        description: data.description || '',
        type: data.type,
        parentId: data.parentId,
      }
      this.dialogVisible = true
    },
    remove(node, data) {
      this.$confirm(`确认删除 ${data.label}?`, '提示', {
        type: 'warning'
      }).then(() => {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.id === data.id)
        children.splice(index, 1)
      })
    },
    confirmDialog() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const newNode = {
            id: this.nextId++,
            label: this.form.name,
            description: this.form.description,
            type: this.form.type,
            parentId: this.form.parentId,
          }

          if (!this.form.parentId) {
            this.diseaseTree.push(newNode)
          } else {
            const parent = this.findNode(this.diseaseTree, this.form.parentId)
            if (parent) {
              if (!parent.children) {
                this.$set(parent, 'children', [])
              }
              parent.children.push(newNode)
            }
          }

          this.dialogVisible = false
        }
      })
    },
    validateName(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入名称'))
        return
      }

      const siblings = this.getSiblings(this.form.parentId)
      if (siblings.some(item => item.label === value)) {
        callback(new Error('名称在同级中必须唯一'))
      } else {
        callback()
      }
    },
    findNode(tree, id) {
      for (const node of tree) {
        if (node.id === id) return node
        if (node.children) {
          const found = this.findNode(node.children, id)
          if (found) return found
        }
      }
      return null
    },
    getSiblings(parentId) {
      if (!parentId) return this.diseaseTree
      const parent = this.findNode(this.diseaseTree, parentId)
      return parent ? parent.children || [] : []
    },
    handleDrop(draggingNode, dropNode, type) {
      console.log('节点位置已变更', draggingNode, dropNode, type)
    },
    handleNodeClick(data) {
      this.currentNode = data
    },
    saveBasicInfo() {
      this.$message.success('基本信息已保存')
    },
    // 生成百度百科链接
    generateEncyclopediaUrl(diseaseName) {
      return `https://baike.baidu.com/item/${encodeURIComponent(diseaseName)}`;
    },
    // 打开百科链接
    openWikiLink() {
      if (this.currentNode && this.currentNode.type === 'disease') {
        const url = this.generateEncyclopediaUrl(this.currentNode.label);
        window.open(url, '_blank');
      } else {
        this.$message.warning('请选择一个疾病节点');
      }
    },
    // 导出Excel方法
    exportToExcel() {
      const tHeader = ['ID', '名称', '类型', '描述', '父ID'];
      const data = this.flattenTree(this.diseaseTree).map(node => ({
        'ID': node.id,
        '名称': node.label,
        '类型': node.type,
        '描述': node.description,
        '父ID': node.parentId || ''
      }));
      exportJsonToExcel(tHeader, data, '疾病分类列表');
    },
    // 扁平化树形结构
    flattenTree(tree) {
      let result = [];
      tree.forEach(node => {
        result.push(node);
        if (node.children) {
          result = result.concat(this.flattenTree(node.children));
        }
      });
      return result;
    },
    // 处理文件上传
    handleFileChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);

        this.diseaseTree = this.buildTree(jsonData);
        this.nextId = Math.max(...this.flattenTree(this.diseaseTree).map(node => node.id)) + 1;
      };
      reader.readAsArrayBuffer(file.raw);
    },
    // 构建树形结构
    buildTree(data) {
      const map = {};
      const roots = [];

      data.forEach(item => {
        map[item.ID] = { ...item, children: [] };
      });

      data.forEach(item => {
        if (item['父ID']) {
          const parent = map[item['父ID']];
          if (parent) {
            parent.children.push(map[item.ID]);
          }
        } else {
          roots.push(map[item.ID]);
        }
      });

      return roots.map(node => {
        return {
          id: node.ID,
          label: node.名称,
          type: node.类型,
          description: node.描述,
          parentId: node['父ID'] || null,
          children: node.children.map(child => ({
            id: child.ID,
            label: child.名称,
            type: child.类型,
            description: child.描述,
            parentId: child['父ID'] || null,
            children: child.children
          }))
        };
      });
    }
  },
  created() {
    this.diseaseTree = [
      {
        id: 1,
        label: '心血管疾病',
        type: 'category',
        children: [
          {
            id: 2,
            label: '冠心病',
            type: 'category',
            children: [
              { 
                id: 3, 
                label: '心绞痛', 
                type: 'disease', 
                description: '心绞痛是一种常见的心血管疾病症状...',
              }
            ]
          }
        ]
      },
      {
        id: 4,
        label: '罕见病',
        type: 'category',
        children: [
          {
            id: 5,
            label: '代谢性罕见病',
            type: 'category',
            children: [
              { 
                id: 6, 
                label: '苯丙酮尿症', 
                type: 'disease', 
                description: '苯丙酮尿症是一种常见的氨基酸代谢病...',
              }
            ]
          }
        ]
      }
    ]
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-buttons {
  display: flex;
  gap: 8px;
}
/* 新增卡片宽度样式 */
.el-col:first-child .el-card {
  width: 100%;
  min-width: 415px; /* 进一步增加到400px */
}
</style>